<template>
  <div>
    <el-dialog v-model="Visible" title="自定义模板" width="700">
      <el-form :model="form" label-position="top">
        <el-form-item label="模板名称">
          <el-select
            v-model="form.label"
            placeholder="你选择模板名称"
            @change="handleClick"
          >
            <el-option
              :label="item.templateName"
              :value="item.templateCode"
              v-for="item in options"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="自定义内容">
          <el-input
            v-model="form.text"
            style="width: 100%"
            :rows="16"
            type="textarea"
            placeholder="请输入模板自定义内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Visible = false">取消</el-button>
          <el-button type="primary" @click="handleOk"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, defineExpose } from "vue";
import { templateList, textCode, textUpdate } from "@/api/index.js";
import { ElMessage } from "element-plus";

const Visible = ref(false);
const form = ref({});
const options = ref([]);
const pre = ref({});

const handleOk = () => {
  textUpdate({ ...pre.value, text: form.value.text }).then(() => {
    Visible.value = false;
    ElMessage({
      message: "保存成功",
      type: "warning",
    });
  });
};

const handleClick = () => {
  form.value.text = "";
  textCode(form.value.label).then((res) => {
    const {
      data: { code, data: d1, message },
    } = res;
    if (code == 500) {
      ElMessage({
        message: message,
        type: "warning",
      });

      pre.value = {
        id: "",
        templateName: options.value.find(
          (item) => item.templateCode == form.value.label
        ).templateName,
        templateCode: form.value.label,
      };
      return;
    }
    form.value.text = d1.text;
    pre.value = {
      id: d1.id,
      templateName: d1.templateName,
      templateCode: d1.templateCode,
    };
  });
};

const handleOpen = () => {
  Visible.value = true;
  form.value = {};
  templateList().then((res) => {
    const {
      data: { data },
    } = res;
    options.value = data;
  });
};
defineExpose({
  handleOpen,
});
</script>
<style scoped></style>
